package com.gq.dragonball;


import java.util.ArrayList;
import java.util.Hashtable;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.gq.tab.scr.ImageDetailSrc;
import com.gq.utils.CustomViewPager;
import com.rtst.widget.tab.SwipeyTabs;
import com.rtst.widget.tab.SwipeyTabsAdapter;

public class ImageDetailActivity extends FragmentActivity {
	private SwipeyTabs mTabs;
	private CustomViewPager mViewPager;
	private String[] TITLES;
	private ArrayList<String> data;
	private SwipeyTabsPagerAdapter adapter;
	private AdView adView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getIntent().getExtras();
		this.data = bundle.getStringArrayList("IMAGES");
		TITLES = new String[data.size()];
		for (int i = 0; i < data.size(); i ++) {
			TITLES[i] = "" + (i + 1) + "/" + data.size();
		}
		int chapter = bundle.getInt("CHAPTER");
		MainActivity.getInstance().trackPageView(String.format("chapter-%d", chapter));
		setContentView(R.layout.activity_custom_swipeytab);
		adView = (AdView) findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest();
		adView.loadAd(adRequest);
		mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		adapter = new SwipeyTabsPagerAdapter(this, getSupportFragmentManager());
		mViewPager = (CustomViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
//		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				mTabs.onPageSelected(position);
				adView.loadAd(new AdRequest());
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				mTabs.onPageScrolled(position, positionOffset, positionOffsetPixels);
			}
			
			@Override
			public void onPageScrollStateChanged(int state) {
				mTabs.onPageScrollStateChanged(state);
			}
		});
		mViewPager.setCurrentItem(0);
		mViewPager.forceDisablePaging();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.none, menu);

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}
	
	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements SwipeyTabsAdapter {
		private final Context mContext;
//		private ImageDetailSrc[] views = new ImageDetailSrc[data.size()];
//		private LinkedList<ImageDetailSrc> views = new LinkedList<ImageDetailSrc>();
		private Hashtable<Integer, ImageDetailSrc> views = new Hashtable<Integer, ImageDetailSrc>();
		private boolean[] disposed = new boolean[data.size()];
		
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}
		
		@Override
		public Fragment getItem(int position) {
			ImageDetailSrc item = null;
			try {
				 item = views.get(position);
			} catch(IndexOutOfBoundsException e) {
				e.printStackTrace();
			}
			if (item == null) {
				String url = data.get(position);
				item = new ImageDetailSrc(url, mViewPager, mTabs);
				views.put(position, item);
			}
			return item;
		}
		
		@Override
		public int getCount() {
			return TITLES.length;
		}
		
		public ViewGroup getTab(final int position, SwipeyTabs root) {
			ViewGroup layout = (ViewGroup) LayoutInflater.from(mContext)
					.inflate(R.layout.swipey_tab_indicator, root, false);
		
			TextView view = (TextView) layout.findViewById(R.id.swipey_tab);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			return layout;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			if (position+1<getCount() && position>0) getItem(position+1);
			ImageDetailSrc item = null;
			try {
				item = views.get(position);
				if (item != null && disposed[position] == true) {
					disposed[position] = false;
					item.getImageViewPager().getImageView().prepareDownload(data.get(position));
				}
			} catch(Exception e) {
			}
			int currentPos = mViewPager.getCurrentItem();
			if (currentPos - 5 >= 0 && disposed[currentPos - 5]) {
				disposed[currentPos - 5] = false;
				views.get(currentPos - 5).getImageViewPager().getImageView().prepareDownload(data.get(currentPos - 5));
			}
			if (currentPos + 5 < getCount() && disposed[currentPos+5]) {
				disposed[currentPos + 5] = false;
				try {
					views.get(currentPos + 5).getImageViewPager().getImageView().prepareDownload(data.get(currentPos + 5));
				} catch(Exception e) {
				}
			}
			return super.instantiateItem(container, position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			int currentPos = mViewPager.getCurrentItem();
			for(int i=0;i<currentPos-5;i++) {
				try {
					ImageDetailSrc item = views.get(i);
					if (item != null) {
						item.dispose();
						disposed[i] = true;
					}
				} catch(Exception e) {
					break;
				}
			}
			for(int i=getCount()-1;i>=currentPos+5;i--) {
				try {
					ImageDetailSrc item = views.get(i);
					if (item != null) {
						item.dispose();
						disposed[i] = true;
					}
				} catch(Exception e) {
					break;
				}
			}
		}
		
		public void disposeAll() {
			for(int i=0;i<views.size();i++) {
				try {
					views.get(i).dispose();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			views.clear();
		}
	}

	@Override
	protected void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		adapter.disposeAll();
		super.onDestroy();
	}
	
}
